<?php
/**
 * 财政资金划入
 */
function financeinput_create(){
	  //我们为这个页面设置标题
	 drupal_set_title('新增财政资金划入');
	 $page_content = l('查看财政资金划入记录','fundmanage/financeinput/list') . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('financeinput_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function financeinput_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增财政资金划入');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['financeinput_form'])){
	  drupal_goto('fundmanage/financeinput/create');
	 }else{
	 }
	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('financeinput_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function financeinput_exportcsv_page(){
  $filename = '财政资金划入.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','划入时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('finance_input', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }

  
}

function financeinput_list_page() {
 
  //$html = l('添加财政资金划入','fundmanage/financeinput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
  	 $html = l('添加记录','fundmanage/financeinput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/financeinput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';
  
  $html .= '<div id="printable_div">';
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '划入时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '附件', 'field' => 'file'),
      array('data' => '更多附件管理', 'field' => 'file'),
      );
  $query = db_select('finance_input', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
       'file_name',
       'url',
      ));
  $results = $query
      ->execute();

  $rows = array();
  $perlink = '';
  foreach ($results as $node) {

  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/financeinput/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
	  
	  $filelink = '';
	  if($node->file_name!='')
	  	$filelink = l($node->file_name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$node->url);

	  $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        //format_date($node->timestamp, 'custom', 'Y-m-d'),
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        $filelink,
        l('附件列表管理', 'jilu_file/create/jiluid/'.$node->id)
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有划入记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  return ($html); 
}

function financeinput_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看财政资金划入记录','fundmanage/financeinput/list') . '<br />'. '<br />';  
  drupal_set_title('管理该项财政资金划入记录');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('financeinput_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function financeinput_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['financeinput_form']['serial_number'])?$_SESSION['financeinput_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('划入资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['financeinput_form']['amount'])?$_SESSION['financeinput_form']['amount']:"",
 );
 $datetime = $_SESSION['financeinput_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('划入时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['financeinput_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['financeinput_form']['remark'])?$_SESSION['financeinput_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('financeinput_confirm_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function financeinput_form(){
	  //添加我们自己的CSS，用来控制表单的样式
	 //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
	 
	  //提示信息，默认为markup类型。
	 $count_serialnum = 1;
	 $query = db_select('finance_input', 'n') 
      ->fields ('n', array (
      'id',
      'serial_number',
      ));
	  $results = $query
	      ->execute();
      $maxno = 0;
	  foreach ($results as $node) {
        $ser_num = intval(substr($node->serial_number, 4, 4));
        if ($ser_num > $maxno) $maxno = $ser_num;
	  }
    $count_serialnum = $maxno + 1;
     if($count_serialnum<10)
	 	$count_serialnum = '000'.$count_serialnum;
	 elseif ($count_serialnum<100) {
		$count_serialnum = '00'.$count_serialnum; 
	 }
	 elseif ($count_serialnum<1000) {
		$count_serialnum = '0'.$count_serialnum; 
	 }
	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['financeinput_form']['serial_number'])?$_SESSION['financeinput_form']['serial_number']:"czhr".$count_serialnum,
	  //'#description' => t('例如：czsr01'),
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('划入资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['financeinput_form']['amount'])?$_SESSION['financeinput_form']['amount']:"",
	  '#description' => t('例如：250.55'),
	 );
	 
	 $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('划入时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['financeinput_form']['remark'])?$_SESSION['financeinput_form']['remark']:"",
	 );
	 
	  $form['upload'] = array(
	   '#type' => 'managed_file',
	   '#title' => '附件上传',
	   '#required' => FALSE,
	   '#upload_location' => 'public://my_uploads',
	   '#upload_validators' => array(
	     'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		 'file_validate_size' => array(50*1024*1024)),
	 );
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => FALSE,
	  '#default_value' =>"附件",
	 );	
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function financeinput_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['amount']) > 10) {
	    form_set_error('amount', '要求精度小于10 个字符');
	  } 
	  if (!($form_state['values']['amount']>0)) {
	    form_set_error('amount', '请输入正数');
	  } 
	  
}

function financeinput_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['financeinput_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 //$form_state['redirect'] = 'fundmanage/financeinput/confirm';
	 
	 /**
	   * 写入数据库
	   */
	   
	$values = NULL;
    //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	if(empty($_SESSION['financeinput_form'])){
	 //drupal_goto('contact');
		$form_state['redirect'] = 'fundmanage/financeinput/create';
	}else{
		$values = $_SESSION['financeinput_form'];
		unset($_SESSION['financeinput_form']);
    }
	  
	$fid = $form_state['values']['upload']; 
	$file = file_load($fid);  
	
	if ($file != null) {
		$filename = $values['file_name'];
		if($filename == "")
			$filename = "附件";
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
		  
	      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('finance_input')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'url' => $saveurl,
		   		 'file_name' => $filename,	 
			     'file_managed_id' => $fid,
	  			))->execute();
		  if ($last_id!=NULL) {
			// $form_state['redirect'] = 'fundmanage/financeinput/list/'.$last_id;
			$form_state['redirect'] = 'fundmanage/financeinput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	  } 
	  else {
		  form_set_error('upload',$extension_errors[0]); 
	  }
	}
	else{
		$datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('finance_input')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/financeinput/list/'.$last_id;
			 $form_state['redirect'] = 'fundmanage/financeinput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	}
}
 
function financeinput_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/financeinput/create';
}

function financeinput_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['financeinput_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/financeinput/create';
	  }else{
		  $values = $_SESSION['financeinput_form'];
		  unset($_SESSION['financeinput_form']);
	  }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('finance_input')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		 //$form_state['redirect'] = 'fundmanage/financeinput/list/'.$last_id;
		 $form_state['redirect'] = 'fundmanage/financeinput/list';
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function financeinput_edit_form($form, &$form_state, $perid){
  $query = "SELECT serial_number,amount,timestamp,remark,file_name, url, file_managed_id  FROM " .
           "{finance_input} where id = ?";
  $queryResult = db_query($query, array($perid));
  
  foreach ($queryResult as $links ) {
  	$datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
	$amount = $links->amount;
    $remark = $links->remark;
    $file_name =  $links->file_name;
	$url =  $links->url;
	$file_managed_id = $links->file_managed_id;
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id); 
   $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['financeinput_edit_form']['serial_number'])?$_SESSION['financeinput_edit_form']['serial_number']:$serial_number,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('划入资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['financeinput_edit_form']['amount'])?$_SESSION['financeinput_edit_form']['amount']:$amount,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('划入时间'),
	     '#default_value' => isset($_SESSION['financeinput_edit_form']['timestamp'])?$_SESSION['financeinput_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['financeinput_edit_form']['remark'])?$_SESSION['financeinput_edit_form']['remark']:$remark,
	 );
	 
	  $form['file_name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => FAlSE,
	  '#default_value' =>isset($_SESSION['financeinput_edit_form']['file_name'])?$_SESSION['financeinput_edit_form']['file_name']:$file_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交附件',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(50*1024*1024)),
	);
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	  
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    //'#value' => t('删除该财政资金划入记录'),
	    '#value' => t('删除该记录'),
	    '#submit' => array('financeinput_edit_form_deleate'),
	  );
  	
	 
  }
  

  return $form;
}

function financeinput_edit_form_submit($form, &$form_state){
	$values = NULL;
	$values = $form_state['values'];
    $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
    $fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	$filename = $values['file_name'];
	if($filename == "")
		$filename = "附件";
	$filemanagedid = $values['file_managed_id'];
	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}
			  db_update('finance_input')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
				   	 'url' => $saveurl,
				   	 'file_managed_id' => $fid,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 //$form_state['redirect'] = 'fundmanage/financeinput/list/'.$values['bid'];
			 $form_state['redirect'] = 'fundmanage/financeinput/list';
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		 db_update('finance_input')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 //$form_state['redirect'] = 'fundmanage/financeinput/list/'.$values['bid'];
			 $form_state['redirect'] = 'fundmanage/financeinput/list';
	}
}

function financeinput_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['financeinput_edit_form'] = $form_state['values'];
	 $values = $_SESSION['financeinput_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/financeinput/deleate/'.$values['bid'];
}

function financeinput_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该财政资金划入记录将不可恢复！';
  
  drupal_set_title('删除该财政资金划入记录');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('financeinput_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function financeinput_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('financeinput_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function financeinput_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['financeinput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/financeinput/list';
	  }else{
		  $values = $_SESSION['financeinput_edit_form'];
		  unset($_SESSION['financeinput_edit_form']);
		  $form_state['redirect'] = 'fundmanage/financeinput/list/'.$values['bid'];
	  }
}

function financeinput_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['financeinput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/financeinput/list';
	  }else{
		  $values = $_SESSION['financeinput_edit_form'];
		  unset($_SESSION['financeinput_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('finance_input')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'fundmanage/financeinput/list';;
	  }

}

/**
 *参股基金收入
 */
function profitinput_create(){
	  //我们为这个页面设置标题
	 drupal_set_title('新增参股基金收入');
	 $page_content = l('查看参股基金收入记录','fundmanage/profitinput/list') . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('profitinput_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function profitinput_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增参股基金收入');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['profitinput_form'])){
	  drupal_goto('fundmanage/profitinput/create');
	 }else{
	 }
	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('profitinput_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function profitinput_exportcsv_page(){
  $filename = '参股基金收入.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','划入时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('profit_input', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }

  
}

function profitinput_list_page() {
 
  //$html = l('添加参股基金收入','fundmanage/profitinput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
  	$html = l('添加记录','fundmanage/profitinput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/profitinput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '划入时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '附件', 'field' => 'file'),
       array('data' => '更多附件管理', 'field' => 'file_list'),
      );
  $query = db_select('profit_input', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
       'file_name',
       'url',
      ));
  $results = $query
      ->execute();

  $rows = array();
  
  $perlink = '';
  foreach ($results as $node) {
  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/profitinput/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
	   $filelink = '';
	  if($node->file_name!='')
	  	$filelink = l($node->file_name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$node->url);
	  
      $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        $filelink,
         l('附件列表管理', 'jilu_file/create/jiluid/'.$node->id)
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有参股基金收入记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function profitinput_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看参股基金收入记录','fundmanage/profitinput/list') . '<br />'. '<br />';
  drupal_set_title('管理该项参股基金收入记录');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('profitinput_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function profitinput_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['profitinput_form']['serial_number'])?$_SESSION['profitinput_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('划入资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['profitinput_form']['amount'])?$_SESSION['profitinput_form']['amount']:"",
 );
 $datetime = $_SESSION['profitinput_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('划入时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['profitinput_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['profitinput_form']['remark'])?$_SESSION['profitinput_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('profitinput_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function profitinput_form(){
	  //添加我们自己的CSS，用来控制表单的样式
	 //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
	 $count_serialnum = 1;
	 $query = db_select('profit_input', 'n') 
      ->fields ('n', array (
      'id',
      'serial_number',
      ));
	  $results = $query
	      ->execute();
    $maxno = 0;
    foreach ($results as $node) {
        $ser_num = intval(substr($node->serial_number, 4, 4));
        if ($ser_num > $maxno) $maxno = $ser_num;
    }
    $count_serialnum = $maxno + 1;
     if($count_serialnum<10)
	 	$count_serialnum = '000'.$count_serialnum;
	 elseif ($count_serialnum<100) {
		$count_serialnum = '00'.$count_serialnum; 
	 }
	 elseif ($count_serialnum<1000) {
		$count_serialnum = '0'.$count_serialnum; 
	 }
	 
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['profitinput_form']['serial_number'])?$_SESSION['profitinput_form']['serial_number']:"cghr".$count_serialnum,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('划入资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['profitinput_form']['amount'])?$_SESSION['profitinput_form']['amount']:"",
	  '#description' => t('例如：250.55'),
	 );
	 
	 $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('划入时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['profitinput_form']['remark'])?$_SESSION['profitinput_form']['remark']:"",
	 );
	 
	 $form['upload'] = array(
	   '#type' => 'managed_file',
	   '#title' => '附件上传',
	   '#required' => FALSE,
	   '#upload_location' => 'public://my_uploads',
	   '#upload_validators' => array(
	     'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		 'file_validate_size' => array(50*1024*1024)),
	 );
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => FALSE,
	  '#default_value' =>"附件",
	 );	
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function profitinput_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['amount']) > 10) {
	    form_set_error('amount', '要求精度小于10 个字符');
	  } 
	  if (!($form_state['values']['amount']>0)) {
	    form_set_error('amount', '请输入正数');
	  } 
}

function profitinput_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['profitinput_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 //$form_state['redirect'] = 'fundmanage/profitinput/confirm';
	  /**
	   * 写入数据库
	   */
	   
	$values = NULL;
    //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	if(empty($_SESSION['profitinput_form'])){
	 //drupal_goto('contact');
		$form_state['redirect'] = 'fundmanage/profitinput/create';
	}else{
		$values = $_SESSION['profitinput_form'];
		unset($_SESSION['profitinput_form']);
    }
	  
	$fid = $form_state['values']['upload']; 
	$file = file_load($fid);  
	
	if ($file != null) {
		$filename = $values['file_name'];
		if($filename == "")
			$filename = "附件";
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
		  
	      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('profit_input')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'url' => $saveurl,
		   		 'file_name' => $filename,	 
			     'file_managed_id' => $fid,
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/profitinput/list/'.$last_id;
			 $form_state['redirect'] = 'fundmanage/profitinput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	  } 
	  else {
		  form_set_error('upload',$extension_errors[0]); 
	  }
	}
	else{
		$datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('profit_input')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/profitinput/list/'.$last_id;
			 $form_state['redirect'] = 'fundmanage/profitinput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	}
}
 
function profitinput_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/profitinput/create';
}

function profitinput_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['profitinput_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/profitinput/create';
	  }else{
		  $values = $_SESSION['profitinput_form'];
		  unset($_SESSION['profitinput_form']);
	  }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('profit_input')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		 //$form_state['redirect'] = 'fundmanage/profitinput/list/'.$last_id;
		 $form_state['redirect'] = 'fundmanage/profitinput/list';
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function profitinput_edit_form($form, &$form_state, $perid){
  
 $query = "SELECT serial_number,amount,timestamp,remark,file_name, url, file_managed_id   FROM " .
           "{profit_input} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	$datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
	$amount = $links->amount;
    $remark = $links->remark;
	$file_name =  $links->file_name;
	$url =  $links->url;
	$file_managed_id = $links->file_managed_id;
	//$page_content = str_replace(array("\n", "\r\n") , "<br />", $page_content);
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id); 
   $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['profitinput_edit_form']['serial_number'])?$_SESSION['profitinput_edit_form']['serial_number']:$serial_number,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('划入资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['profitinput_edit_form']['amount'])?$_SESSION['profitinput_edit_form']['amount']:$amount,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('划入时间'),
	     '#default_value' => isset($_SESSION['profitinput_edit_form']['timestamp'])?$_SESSION['profitinput_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['profitinput_edit_form']['remark'])?$_SESSION['profitinput_edit_form']['remark']:$remark,
	 );
	 
	 $form['file_name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => FAlSE,
	  '#default_value' =>isset($_SESSION['profitinput_edit_form']['file_name'])?$_SESSION['profitinput_edit_form']['file_name']:$file_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交附件',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(50*1024*1024)),
	 );
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	   // '#value' => t('删除该参股基金收入记录'),
	   '#value' => t('删除该记录'),
	    '#submit' => array('profitinput_edit_form_deleate'),
	  );
  }
  return $form;
}

function profitinput_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	 
	  $fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	$filename = $values['file_name'];
	if($filename == "")
		$filename = "附件";
	$filemanagedid = $values['file_managed_id'];
	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}
			  db_update('profit_input')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
				   	 'url' => $saveurl,
				   	 'file_managed_id' => $fid,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 //$form_state['redirect'] = 'fundmanage/profitinput/list/'.$values['bid'];
			 $form_state['redirect'] = 'fundmanage/profitinput/list';
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		  db_update('profit_input')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
   			 'file_name' => $filename,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 //$form_state['redirect'] = 'fundmanage/profitinput/list/'.$values['bid'];
	 $form_state['redirect'] = 'fundmanage/profitinput/list';
}
}

function profitinput_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['profitinput_edit_form'] = $form_state['values'];
	 $values = $_SESSION['profitinput_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/profitinput/deleate/'.$values['bid'];
}

function profitinput_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该参股基金收入记录将不可恢复！';
  
  drupal_set_title('删除该参股基金收入记录');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('profitinput_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function profitinput_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('profitinput_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function profitinput_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['profitinput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/profitinput/list';
	  }else{
		  $values = $_SESSION['profitinput_edit_form'];
		  unset($_SESSION['profitinput_edit_form']);
		  $form_state['redirect'] = 'fundmanage/profitinput/list/'.$values['bid'];
	  }
}

function profitinput_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['profitinput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/profitinput/list';
	  }else{
		  $values = $_SESSION['profitinput_edit_form'];
		  unset($_SESSION['profitinput_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('profit_input')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'fundmanage/profitinput/list';;
	  }

}

/**
 *利息净营收
 */
function interestinput_create(){
      //我们为这个页面设置标题
     drupal_set_title('新增利息净营收');
     $page_content = l('查看利息净营收记录','fundmanage/interestinput/list') . '<br />'. '<br />';
     $render_array = array(
       '#markup' => $page_content, 
     );
     
     //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
     $form = drupal_get_form('interestinput_form');
     $render_array['#markup'] .= drupal_render($form);
     
     //Drupal7的页面回调，返回的应该是一个数组
     return $render_array;
}

function interestinput_confirm_page(){
  //我们为这个页面设置标题
     drupal_set_title('新增利息净营收');
     
     //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
     if(empty($_SESSION['interestinput_form'])){
      drupal_goto('fundmanage/interestinput/create');
     }else{
     }
    
     $render_array = array(
       '#markup' => '', 
     );
     //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
     $form = drupal_get_form('interestinput_confirm_form');
     $render_array['#markup'] .= drupal_render($form);
     //Drupal7的页面回调，返回的应该是一个数组
     return $render_array;
}

function interestinput_exportcsv_page(){
  $filename = '利息净营收.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','划入时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('interest_input', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
      $str = implode(',', $values) ."\r\n";
      $str = iconv('utf-8','gb2312',$str);
      print $str;
    }

  
}

function interestinput_list_page() {
 
  //$html = l('添加利息净营收','fundmanage/interestinput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
  	$html = l('添加记录','fundmanage/interestinput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/interestinput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '划入时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '附件', 'field' => 'file'),
       array('data' => '更多附件管理', 'field' => 'file_list'),
      );
  $query = db_select('interest_input', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
       'file_name',
       'url',
      ));
  $results = $query
      ->execute();

  $perlink = '';
  $rows[] = array();
  foreach ($results as $node) {
  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/interestinput/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
	  $filelink = '';
	  if($node->file_name!='')
	  	$filelink = l($node->file_name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$node->url);
      $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        $filelink,
         l('附件列表管理', 'jilu_file/create/jiluid/'.$node->id)
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有利息净营收记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function interestinput_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看利息净营收记录','fundmanage/interestinput/list') . '<br />'. '<br />';
  drupal_set_title('管理该项利息净营收记录');
     
  $render_array = array(
       '#markup' => $page_content,
     );
     
     //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('interestinput_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
     
     //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function interestinput_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['interestinput_form']['serial_number'])?$_SESSION['interestinput_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('划入资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['interestinput_form']['amount'])?$_SESSION['interestinput_form']['amount']:"",
 );
 $datetime = $_SESSION['interestinput_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('划入时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['interestinput_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['interestinput_form']['remark'])?$_SESSION['interestinput_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('interestinput_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function interestinput_form(){
      //添加我们自己的CSS，用来控制表单的样式
     //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
     $count_serialnum = 1;
	 $query = db_select('interest_input', 'n') 
      ->fields ('n', array (
      'id',
      'serial_number',
      ));
	  $results = $query
	      ->execute();
    $maxno = 0;
    foreach ($results as $node) {
        $ser_num = intval(substr($node->serial_number, 4, 4));
        if ($ser_num > $maxno) $maxno = $ser_num;
    }
    $count_serialnum = $maxno + 1;
     if($count_serialnum<10)
	 	$count_serialnum = '000'.$count_serialnum;
	 elseif ($count_serialnum<100) {
		$count_serialnum = '00'.$count_serialnum; 
	 }
	 elseif ($count_serialnum<1000) {
		$count_serialnum = '0'.$count_serialnum; 
	 }
      //提示信息，默认为markup类型。
     $form['tips'] = array(
      '#prefix' =>'<div id="tips">',
      '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
      '#suffix' =>'</div>',
     );
     
     $form['serial_number'] = array(
      '#title' => t('编号'),
      '#type' => 'textfield',
      '#required' => TRUE,
      '#default_value' =>isset($_SESSION['interestinput_form']['serial_number'])?$_SESSION['interestinput_form']['serial_number']:"lxsr".$count_serialnum,
     // '#description' => t('例如：cgjjjys01'),
     );
     
     $form['amount'] = array(
      '#title' => t('划入资金金额（单位：元）'),
      '#type' => 'textfield',
      '#required' => TRUE,
      '#default_value' =>isset($_SESSION['interestinput_form']['amount'])?$_SESSION['interestinput_form']['amount']:"",
      '#description' => t('例如：250.55'),
     );
     
     $today = getdate();

      $form['timestamp'] = array(
         '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
         '#title' => t('划入时间'),
         '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
      );
     
     $form['remark'] = array(
      '#title' => t('备注'),
      '#type' => 'textarea',
      '#required' => FALSE,
      '#default_value' =>isset($_SESSION['interestinput_form']['remark'])?$_SESSION['interestinput_form']['remark']:"",
     );
     
	 $form['upload'] = array(
	   '#type' => 'managed_file',
	   '#title' => '附件上传',
	   '#required' => FALSE,
	   '#upload_location' => 'public://my_uploads',
	   '#upload_validators' => array(
	     'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		 'file_validate_size' => array(50*1024*1024)),
	 );
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => FALSE,
	  '#default_value' =>"附件",
	 );	
	 
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('确认'),
      );
      return $form;
}

function interestinput_form_validate($form, &$form_state){
      if (drupal_strlen($form_state['values']['amount']) > 10) {
        form_set_error('amount', '要求精度小于10 个字符');
      } 
      if (!($form_state['values']['amount']>0)) {
        form_set_error('amount', '请输入正数');
      } 
}

function interestinput_form_submit($form, &$form_state){
      //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
     $_SESSION['interestinput_form'] = $form_state['values'];
     //表单重定向到确认页面
     //$form_state['redirect'] = 'fundmanage/interestinput/confirm';
      /**
	   * 写入数据库
	   */
	   
	$values = NULL;
    //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	if(empty($_SESSION['interestinput_form'])){
	 //drupal_goto('contact');
		$form_state['redirect'] = 'fundmanage/interestinput/create';
	}else{
		$values = $_SESSION['interestinput_form'];
		unset($_SESSION['interestinput_form']);
    }
	  
	$fid = $form_state['values']['upload']; 
	$file = file_load($fid);  
	
	if ($file != null) {
		$filename = $values['file_name'];
		if($filename == "")
			$filename = "附件";
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
		  
	      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('interest_input')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'url' => $saveurl,
		   		 'file_name' => $filename,	 
			     'file_managed_id' => $fid,
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/interestinput/list/'.$last_id;
		     $form_state['redirect'] = 'fundmanage/interestinput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	  } 
	  else {
		  form_set_error('upload',$extension_errors[0]); 
	  }
	}
	else{
		$datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('interest_input')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/interestinput/list/'.$last_id;
		  $form_state['redirect'] = 'fundmanage/interestinput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	}
}
 
function interestinput_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/interestinput/create';
}

function interestinput_confirm_form_submit($form, &$form_state){
        /**
       * 写入数据库
       */
       $values = NULL;
       //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
      if(empty($_SESSION['interestinput_form'])){
          //drupal_goto('contact');
          $form_state['redirect'] = 'fundmanage/interestinput/create';
      }else{
          $values = $_SESSION['interestinput_form'];
          unset($_SESSION['interestinput_form']);
      }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
      $last_id = db_insert('interest_input')
        ->fields(array(
             'serial_number' => $values['serial_number'],
             'amount' => $values['amount'],
             'timestamp' =>  $datetime,
             'remark' => $values['remark'],
            ))->execute();
      if ($last_id!=NULL) {
         //$form_state['redirect'] = 'fundmanage/interestinput/list/'.$last_id;
		 $form_state['redirect'] = 'fundmanage/interestinput/list';
      } else {
        
        // 数据写入失败了
        drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
        
      } 
}

function interestinput_edit_form($form, &$form_state, $perid){
  
 $query = "SELECT serial_number,amount,timestamp,remark,file_name, url, file_managed_id  FROM " .
           "{interest_input} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
    $datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
    $amount = $links->amount;
    $remark = $links->remark;
	$file_name =  $links->file_name;
	$url =  $links->url;
	$file_managed_id = $links->file_managed_id;
    //$page_content = str_replace(array("\n", "\r\n") , "<br />", $page_content);
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id); 
   $form['serial_number'] = array(
      '#title' => t('编号'),
      '#type' => 'textfield',
      '#required' => TRUE,
      '#default_value' =>isset($_SESSION['interestinput_edit_form']['serial_number'])?$_SESSION['interestinput_edit_form']['serial_number']:$serial_number,
     );
     
     $form['amount'] = array(
      '#title' => t('划入资金金额（单位：元）'),
      '#type' => 'textfield',
      '#required' => TRUE,
      '#default_value' =>isset($_SESSION['interestinput_edit_form']['amount'])?$_SESSION['interestinput_edit_form']['amount']:$amount,
     );
     
      $form['timestamp'] = array(
         '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
         '#title' => t('划入时间'),
         '#default_value' => isset($_SESSION['interestinput_edit_form']['timestamp'])?$_SESSION['interestinput_edit_form']['timestamp']:
            array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
      );
     
     $form['remark'] = array(
      '#title' => t('备注'),
      '#type' => 'textarea',
      '#required' => FALSE,
      '#default_value' =>isset($_SESSION['interestinput_edit_form']['remark'])?$_SESSION['interestinput_edit_form']['remark']:$remark,
     );
    
	 $form['file_name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => FAlSE,
	  '#default_value' =>isset($_SESSION['interestinput_edit_form']['file_name'])?$_SESSION['interestinput_edit_form']['file_name']:$file_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交附件',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(50*1024*1024)),
	 );
	 
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('提交修改'),
      );
     //表单元素“提交”按钮
      $form['deleate'] = array(
        '#type' => 'submit',
        //'#value' => t('删除该利息净营收记录'),
        '#value' => t('删除该记录'),
        '#submit' => array('interestinput_edit_form_deleate'),
      );
  }
  return $form;
}

function interestinput_edit_form_submit($form, &$form_state){
  	 $values = NULL;
	  $values = $form_state['values'];
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	 
	  $fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	$filename = $values['file_name'];
	if($filename == "")
		$filename = "附件";
	$filemanagedid = $values['file_managed_id'];
	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}
			  db_update('interest_input')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
				   	 'url' => $saveurl,
				   	 'file_managed_id' => $fid,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 //$form_state['redirect'] = 'fundmanage/interestinput/list/'.$values['bid'];
			 $form_state['redirect'] = 'fundmanage/interestinput/list';
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		 db_update('interest_input')
        ->fields(array(
             'serial_number' => $values['serial_number'],
             'amount' => $values['amount'],
             'timestamp' =>  $datetime,
             'remark' => $values['remark'],
             'file_name' => $filename,
            ))
        ->condition('id', $values['bid'])
        ->execute();
     //$form_state['redirect'] = 'fundmanage/interestinput/list/'.$values['bid'];
	 $form_state['redirect'] = 'fundmanage/interestinput/list';
}
}

function interestinput_edit_form_deleate($form, &$form_state){
     $values = NULL;
     $_SESSION['interestinput_edit_form'] = $form_state['values'];
     $values = $_SESSION['interestinput_edit_form'] ;
     //表单重定向到确认页面
     $form_state['redirect'] = 'fundmanage/interestinput/deleate/'.$values['bid'];
}

function interestinput_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该利息净营收记录将不可恢复！';
  
  drupal_set_title('删除该利息净营收记录');
     
     $render_array = array(
       '#markup' => $page_content,
     );
     
     //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
     $form = drupal_get_form('interestinput_deleate_form');
     $render_array['#markup'] .= drupal_render($form);
     
     //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function interestinput_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('interestinput_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function interestinput_deleate_form_back($form, &$form_state){
    if(empty($_SESSION['interestinput_edit_form'])){
          //drupal_goto('contact');
          $form_state['redirect'] = 'fundmanage/interestinput/list';
      }else{
          $values = $_SESSION['interestinput_edit_form'];
          unset($_SESSION['interestinput_edit_form']);
          $form_state['redirect'] = 'fundmanage/interestinput/list/'.$values['bid'];
      }
}

function interestinput_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['interestinput_edit_form'])){
          //drupal_goto('contact');
          $form_state['redirect'] = 'fundmanage/interestinput/list';
      }else{
          $values = $_SESSION['interestinput_edit_form'];
          unset($_SESSION['interestinput_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
          db_delete('interest_input')
            ->condition('id' ,$values['bid'])
            ->execute();
          $form_state['redirect'] = 'fundmanage/interestinput/list';;
      }

}

/**
 *其他收入
 */
function otherinput_create(){
	  //我们为这个页面设置标题
	 drupal_set_title('新增其他收入');
	 $page_content = l('查看其他收入记录','fundmanage/otherinput/list') . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('otherinput_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function otherinput_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增其他收入');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['otherinput_form'])){
	  drupal_goto('fundmanage/profitinput/create');
	 }else{
	 }
	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('otherinput_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function otherinput_exportcsv_page(){
  $filename = '其他收入.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','划入时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('other_input', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }

  
}

function otherinput_list_page() {
 
  //$html = l('添加其他收入','fundmanage/otherinput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
  	$html = l('添加记录','fundmanage/otherinput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/otherinput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '划入时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '附件', 'field' => 'file'),
       array('data' => '更多附件管理', 'field' => 'file_list'),
      );
  $query = db_select('other_input', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
       'id',
       'serial_number',
       'amount',
       'timestamp',
       'remark',
       'file_name',
       'url',
      ));
  $results = $query
      ->execute();
  $rows[] = array();
  $perlink = '';
  foreach ($results as $node) {
  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/otherinput/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
	  $filelink = '';
	  if($node->file_name!='')
	  	$filelink = l($node->file_name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$node->url);
      $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        $filelink,
         l('附件列表管理', 'jilu_file/create/jiluid/'.$node->id)
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有其他收入记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function otherinput_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看其他收入记录','fundmanage/otherinput/list') . '<br />'. '<br />';
  
  drupal_set_title('管理该项其他收入记录');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('otherinput_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function otherinput_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['otherinput_form']['serial_number'])?$_SESSION['otherinput_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('划入资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['otherinput_form']['amount'])?$_SESSION['otherinput_form']['amount']:"",
 );
 $datetime = $_SESSION['otherinput_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('划入时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['otherinput_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['otherinput_form']['remark'])?$_SESSION['otherinput_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('otherinput_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function otherinput_form(){
	  //添加我们自己的CSS，用来控制表单的样式
	 //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
	 $count_serialnum = 1;
	 $query = db_select('other_input', 'n') 
      ->fields ('n', array (
      'id',
      'serial_number',
      ));
	  $results = $query
	      ->execute();
    $maxno = 0;
    foreach ($results as $node) {
        $ser_num = intval(substr($node->serial_number, 4, 4));
        if ($ser_num > $maxno) $maxno = $ser_num;
    }
    $count_serialnum = $maxno + 1;
     if($count_serialnum<10)
	 	$count_serialnum = '000'.$count_serialnum;
	 elseif ($count_serialnum<100) {
		$count_serialnum = '00'.$count_serialnum; 
	 }
	 elseif ($count_serialnum<1000) {
		$count_serialnum = '0'.$count_serialnum; 
	 }
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['otherinput_form']['serial_number'])?$_SESSION['otherinput_form']['serial_number']:"qthr".$count_serialnum,
	  //'#description' => t('例如：qtsr01'),
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('划入资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['otherinput_form']['amount'])?$_SESSION['otherinput_form']['amount']:"",
	  '#description' => t('例如：250.55'),
	 );
	 
	 $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('划入时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['otherinput_form']['remark'])?$_SESSION['otherinput_form']['remark']:"",
	 );
	 
	 $form['upload'] = array(
	   '#type' => 'managed_file',
	   '#title' => '附件上传',
	   '#required' => FALSE,
	   '#upload_location' => 'public://my_uploads',
	   '#upload_validators' => array(
	     'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		 'file_validate_size' => array(50*1024*1024)),
	 );
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => FALSE,
	  '#default_value' =>"附件",
	 );	
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function otherinput_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['amount']) > 10) {
	    form_set_error('amount', '要求精度小于10 个字符');
	  } 
	  if (!($form_state['values']['amount']>0)) {
	    form_set_error('amount', '请输入正数');
	  } 
}

function otherinput_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['otherinput_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 //$form_state['redirect'] = 'fundmanage/otherinput/confirm';
	  /**
	   * 写入数据库
	   */
	   
	$values = NULL;
    //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	if(empty($_SESSION['otherinput_form'])){
	 //drupal_goto('contact');
		$form_state['redirect'] = 'fundmanage/otherinput/create';
	}else{
		$values = $_SESSION['otherinput_form'];
		unset($_SESSION['otherinput_form']);
    }
	  
	$fid = $form_state['values']['upload']; 
	$file = file_load($fid);  
	
	if ($file != null) {
		$filename = $values['file_name'];
		if($filename == "")
			$filename = "附件";
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
		  
	      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('other_input')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'url' => $saveurl,
		   		 'file_name' => $filename,	 
			     'file_managed_id' => $fid,
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/otherinput/list/'.$last_id;
			 $form_state['redirect'] = 'fundmanage/otherinput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	  } 
	  else {
		  form_set_error('upload',$extension_errors[0]); 
	  }
	}
	else{
		$datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('other_input')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'file_name' => $filename,
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/otherinput/list/'.$last_id;
			 $form_state['redirect'] = 'fundmanage/otherinput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	}
}
 
function otherinput_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/otherinput/create';
}

function otherinput_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['otherinput_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/otherinput/create';
	  }else{
		  $values = $_SESSION['otherinput_form'];
		  unset($_SESSION['otherinput_form']);
	  }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('other_input')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		 //$form_state['redirect'] = 'fundmanage/otherinput/list/'.$last_id;
		  $form_state['redirect'] = 'fundmanage/otherinput/list';
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function otherinput_edit_form($form, &$form_state, $perid){
  $query = "SELECT serial_number,amount,timestamp,remark, file_name, url, file_managed_id FROM " .
           "{other_input} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	$datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
	$amount = $links->amount;
    $remark = $links->remark;
	$file_name =  $links->file_name;
	$url =  $links->url;
	$file_managed_id = $links->file_managed_id;
	//$page_content = str_replace(array("\n", "\r\n") , "<br />", $page_content);
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id); 
   $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['otherinput_edit_form']['serial_number'])?$_SESSION['otherinput_edit_form']['serial_number']:$serial_number,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('划入资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['otherinput_edit_form']['amount'])?$_SESSION['otherinput_edit_form']['amount']:$amount,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('划入时间'),
	     '#default_value' => isset($_SESSION['otherinput_edit_form']['timestamp'])?$_SESSION['otherinput_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['otherinput_edit_form']['remark'])?$_SESSION['otherinput_edit_form']['remark']:$remark,
	 );
	 
	 $form['file_name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => FAlSE,
	  '#default_value' =>isset($_SESSION['otherinput_edit_form']['file_name'])?$_SESSION['otherinput_edit_form']['file_name']:$file_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交附件',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(50*1024*1024)),
	 );
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	   // '#value' => t('删除该其他收入记录'),
	    '#value' => t('删除该记录'),
	    '#submit' => array('otherinput_edit_form_deleate'),
	  );
  }
  
  return $form;
}

function otherinput_edit_form_submit($form, &$form_state){
   $values = NULL;
   $values = $form_state['values'];
   $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	 
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	$filename = $values['file_name'];
	if($filename == "")
		$filename = "附件";
	$filemanagedid = $values['file_managed_id'];
	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}
			  db_update('other_input')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
				   	 'url' => $saveurl,
				   	 'file_managed_id' => $fid,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 //$form_state['redirect'] = 'fundmanage/otherinput/list/'.$values['bid'];
			 $form_state['redirect'] = 'fundmanage/otherinput/list';
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		 db_update('other_input')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 //$form_state['redirect'] = 'fundmanage/otherinput/list/'.$values['bid'];
	 $form_state['redirect'] = 'fundmanage/otherinput/list';
}
}

function otherinput_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['otherinput_edit_form'] = $form_state['values'];
	 $values = $_SESSION['otherinput_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/otherinput/deleate/'.$values['bid'];
}

function otherinput_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该其他收入记录将不可恢复！';
  
  drupal_set_title('删除该其他收入记录');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('otherinput_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function otherinput_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('otherinput_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function otherinput_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['otherinput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/otherinput/list';
	  }else{
		  $values = $_SESSION['otherinput_edit_form'];
		  unset($_SESSION['otherinput_edit_form']);
		  $form_state['redirect'] = 'fundmanage/otherinput/list/'.$values['bid'];
	  }
}

function otherinput_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['otherinput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/otherinput/list';
	  }else{
		  $values = $_SESSION['otherinput_edit_form'];
		  unset($_SESSION['otherinput_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('other_input')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'fundmanage/otherinput/list';;
	  }

}

/**
 *基金参股支出
 */
function stockoutput_create(){
	  //我们为这个页面设置标题
	 drupal_set_title('新增基金参股支出');
	 $page_content = l('查看基金参股支出记录','fundmanage/stockoutput/list') . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('stockoutput_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function stockoutput_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增基金参股支出');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['stockoutput_form'])){
	  drupal_goto('fundmanage/profitinput/create');
	 }else{
	 }
	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('stockoutput_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function stockoutput_exportcsv_page(){
  $filename = '基金参股支出.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','支出时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('stock_output', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }

  
}

function stockoutput_list_page() {
 
  //$html = l('添加基金参股支出','fundmanage/stockoutput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
	  $html = l('添加记录','fundmanage/stockoutput/create') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/stockoutput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '支出时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '附件', 'field' => 'file'),
      array('data' => '更多附件管理', 'field' => 'file_list'),
      );
  $query = db_select('stock_output', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
       'file_name',
       'url',
      ));
  $results = $query
      ->execute();

  $rows = array();
  $perlink = '';
  foreach ($results as $node) {
  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/stockoutput/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
	  $filelink = '';
	  if($node->file_name!='')
	  	$filelink = l($node->file_name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$node->url);
      
      $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        $filelink,
         l('附件列表管理', 'jilu_file/create/jiluid/'.$node->id)
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金参股支出记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function stockoutput_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看基金参股支出记录','fundmanage/stockoutput/list') . '<br />'. '<br />';
  drupal_set_title('管理该项基金参股支出记录');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('stockoutput_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function stockoutput_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['stockoutput_form']['serial_number'])?$_SESSION['stockoutput_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('支出资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['stockoutput_form']['amount'])?$_SESSION['stockoutput_form']['amount']:"",
 );
 $datetime = $_SESSION['stockoutput_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('支出时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['stockoutput_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['stockoutput_form']['remark'])?$_SESSION['stockoutput_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('stockoutput_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function stockoutput_form(){
	  //添加我们自己的CSS，用来控制表单的样式
	 //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
	 $count_serialnum = 1;
	 $query = db_select('stock_output', 'n') 
      ->fields ('n', array (
      'id',
      'serial_number',
      ));
	  $results = $query
	      ->execute();
    $maxno = 0;
    foreach ($results as $node) {
        $ser_num = intval(substr($node->serial_number, 4, 4));
        if ($ser_num > $maxno) $maxno = $ser_num;
    }
    $count_serialnum = $maxno + 1;
     if($count_serialnum<10)
	 	$count_serialnum = '000'.$count_serialnum;
	 elseif ($count_serialnum<100) {
		$count_serialnum = '00'.$count_serialnum; 
	 }
	 elseif ($count_serialnum<1000) {
		$count_serialnum = '0'.$count_serialnum; 
	 }
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['stockoutput_form']['serial_number'])?$_SESSION['stockoutput_form']['serial_number']:"jjhc".$count_serialnum,
	  //'#description' => t('例如：jjcgzc01'),
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('支出资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['stockoutput_form']['amount'])?$_SESSION['stockoutput_form']['amount']:"",
	  '#description' => t('例如：250.55'),
	 );
	 
	 $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('支出时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['stockoutput_form']['remark'])?$_SESSION['stockoutput_form']['remark']:"",
	 );
	
	$form['upload'] = array(
	   '#type' => 'managed_file',
	   '#title' => '附件上传',
	   '#required' => FALSE,
	   '#upload_location' => 'public://my_uploads',
	   '#upload_validators' => array(
	     'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		 'file_validate_size' => array(50*1024*1024)),
	 );
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => FALSE,
	  '#default_value' =>"附件",
	 );	
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function stockoutput_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['amount']) > 10) {
	    form_set_error('amount', '要求精度小于10 个字符');
	  } 
	  if (!($form_state['values']['amount']>0)) {
	    form_set_error('amount', '请输入正数');
	  } 
}

function stockoutput_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['stockoutput_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 //$form_state['redirect'] = 'fundmanage/stockoutput/confirm';
	  //$form_state['redirect'] = 'fundmanage/otherinput/confirm';
	  /**
	   * 写入数据库
	   */
	   
	$values = NULL;
    //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	if(empty($_SESSION['stockoutput_form'])){
	 //drupal_goto('contact');
		$form_state['redirect'] = 'fundmanage/stockoutput/create';
	}else{
		$values = $_SESSION['stockoutput_form'];
		unset($_SESSION['stockoutput_form']);
    }
	  
	$fid = $form_state['values']['upload']; 
	$file = file_load($fid);  
	
	if ($file != null) {
		$filename = $values['file_name'];
		if($filename == "")
			$filename = "附件";
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
		  
	      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('stock_output')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'url' => $saveurl,
		   		 'file_name' => $filename,	 
			     'file_managed_id' => $fid,
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/stockoutput/list/'.$last_id;
			 $form_state['redirect'] = 'fundmanage/stockoutput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	  } 
	  else {
		  form_set_error('upload',$extension_errors[0]); 
	  }
	}
	else{
		$datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('stock_output')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/stockoutput/list/'.$last_id;
			  $form_state['redirect'] = 'fundmanage/stockoutput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	}
}
 
function stockoutput_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/stockoutput/create';
}

function stockoutput_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['stockoutput_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/stockoutput/create';
	  }else{
		  $values = $_SESSION['stockoutput_form'];
		  unset($_SESSION['stockoutput_form']);
	  }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('stock_output')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		  //$form_state['redirect'] = 'fundmanage/stockoutput/list/'.$last_id;
		  $form_state['redirect'] = 'fundmanage/stockoutput/list';
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function stockoutput_edit_form($form, &$form_state, $perid){
  $query = "SELECT serial_number,amount,timestamp,remark, file_name, url, file_managed_id FROM " .
           "{stock_output} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	$datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
	$amount = $links->amount;
    $remark = $links->remark;
	$file_name =  $links->file_name;
	$url =  $links->url;
	$file_managed_id = $links->file_managed_id;
	//$page_content = str_replace(array("\n", "\r\n") , "<br />", $page_content);
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id); 
   $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['stockoutput_edit_form']['serial_number'])?$_SESSION['stockoutput_edit_form']['serial_number']:$serial_number,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('支出资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['stockoutput_edit_form']['amount'])?$_SESSION['stockoutput_edit_form']['amount']:$amount,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('支出时间'),
	     '#default_value' => isset($_SESSION['stockoutput_edit_form']['timestamp'])?$_SESSION['stockoutput_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['stockoutput_edit_form']['remark'])?$_SESSION['stockoutput_edit_form']['remark']:$remark,
	 );
	 
	 $form['file_name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => FAlSE,
	  '#default_value' =>isset($_SESSION['stockoutput_edit_form']['file_name'])?$_SESSION['stockoutput_edit_form']['file_name']:$file_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交附件',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(50*1024*1024)),
	 );
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    //'#value' => t('删除该记录'),'#value' => t('删除该基金参股支出记录'),
	    '#value' => t('删除该记录'),
	    '#submit' => array('stockoutput_edit_form_deleate'),
	  );
  }

  return $form;
}

function stockoutput_edit_form_submit($form, &$form_state){
	 
	$values = NULL;
    $values = $form_state['values'];
    $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	 
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	$filename = $values['file_name'];
	if($filename == "")
		$filename = "附件";
	$filemanagedid = $values['file_managed_id'];
	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}
			  db_update('stock_output')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
				   	 'url' => $saveurl,
				   	 'file_managed_id' => $fid,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 //$form_state['redirect'] = 'fundmanage/stockoutput/list/'.$values['bid'];
			 $form_state['redirect'] = 'fundmanage/stockoutput/list';
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		 db_update('stock_output')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
   			 'file_name' => $filename,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 //$form_state['redirect'] = 'fundmanage/stockoutput/list/'.$values['bid'];
	 $form_state['redirect'] = 'fundmanage/stockoutput/list';
	}
}

function stockoutput_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['stockoutput_edit_form'] = $form_state['values'];
	 $values = $_SESSION['stockoutput_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/stockoutput/deleate/'.$values['bid'];
}

function stockoutput_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该基金参股支出记录将不可恢复！';
  
  drupal_set_title('删除该基金参股支出记录');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('stockoutput_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function stockoutput_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('stockoutput_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function stockoutput_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['stockoutput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/stockoutput/list';
	  }else{
		  $values = $_SESSION['stockoutput_edit_form'];
		  unset($_SESSION['stockoutput_edit_form']);
		  $form_state['redirect'] = 'fundmanage/stockoutput/list/'.$values['bid'];
	  }
}

function stockoutput_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['stockoutput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/stockoutput/list';
	  }else{
		  $values = $_SESSION['stockoutput_edit_form'];
		  unset($_SESSION['stockoutput_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('stock_output')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'fundmanage/stockoutput/list';;
	  }

}


/**
 *管理费支出
 */
function managerialoutput_create(){
	  //我们为这个页面设置标题
	 drupal_set_title('新增管理费支出');
	 $page_content = l('查看管理费支出记录','fundmanage/managerialoutput/list') . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('managerialoutput_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function managerialoutput_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增管理费支出');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['managerialoutput_form'])){
	  drupal_goto('fundmanage/profitinput/create');
	 }else{
	 }
	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('managerialoutput_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function managerialoutput_exportcsv_page(){
  $filename = '管理费支出.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','支出时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('managerial_output', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }  
}

function managerialoutput_list_page() {
 
  //$html = l('添加管理费支出','fundmanage/managerialoutput/create') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
	  $html = l('添加记录','fundmanage/managerialoutput/create') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/managerialoutput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '支出时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '附件', 'field' => 'file'),
      array('data' => '更多附件管理', 'field' => 'file_list'),
      );
  $query = db_select('managerial_output', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
       'file_name',
       'url',
      ));
  $results = $query
      ->execute();

  $rows = array();
  $perlink = '';
  foreach ($results as $node) {
  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/managerialoutput/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
	  $filelink = '';
	  if($node->file_name!='')
	  	$filelink = l($node->file_name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$node->url);
      $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        $filelink,
         l('附件列表管理', 'jilu_file/create/jiluid/'.$node->id)
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有管理费支出记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function managerialoutput_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看管理费支出记录','fundmanage/managerialoutput/list') . '<br />'. '<br />';
  
  drupal_set_title('管理该项管理费支出记录');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('managerialoutput_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function managerialoutput_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['managerialoutput_form']['serial_number'])?$_SESSION['managerialoutput_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('支出资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['managerialoutput_form']['amount'])?$_SESSION['managerialoutput_form']['amount']:"",
 );
 $datetime = $_SESSION['managerialoutput_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('支出时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['managerialoutput_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['managerialoutput_form']['remark'])?$_SESSION['managerialoutput_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('managerialoutput_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function managerialoutput_form(){
	  //添加我们自己的CSS，用来控制表单的样式
	 //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
	 $count_serialnum = 1;
	 $query = db_select('managerial_output', 'n') 
      ->fields ('n', array (
      'id',
      'serial_number',
      ));
	  $results = $query
	      ->execute();
    $maxno = 0;
    foreach ($results as $node) {
        $ser_num = intval(substr($node->serial_number, 4, 4));
        if ($ser_num > $maxno) $maxno = $ser_num;
    }
    $count_serialnum = $maxno + 1;
     if($count_serialnum<10)
	 	$count_serialnum = '000'.$count_serialnum;
	 elseif ($count_serialnum<100) {
		$count_serialnum = '00'.$count_serialnum; 
	 }
	 elseif ($count_serialnum<1000) {
		$count_serialnum = '0'.$count_serialnum; 
	 }
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['managerialoutput_form']['serial_number'])?$_SESSION['managerialoutput_form']['serial_number']:"glhc".$count_serialnum,
	  //'#description' => t('例如：glfzc01'),
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('支出资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['managerialoutput_form']['amount'])?$_SESSION['managerialoutput_form']['amount']:"",
	  '#description' => t('例如：250.55'),
	 );
	 
	 $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('支出时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['managerialoutput_form']['remark'])?$_SESSION['managerialoutput_form']['remark']:"",
	 );
	 
	 $form['upload'] = array(
	   '#type' => 'managed_file',
	   '#title' => '附件上传',
	   '#required' => FALSE,
	   '#upload_location' => 'public://my_uploads',
	   '#upload_validators' => array(
	     'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		 'file_validate_size' => array(50*1024*1024)),
	 );
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => FALSE,
	  '#default_value' =>"附件",
	 );	
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function managerialoutput_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['amount']) > 10) {
	    form_set_error('amount', '要求精度小于10 个字符');
	  } 
	  if (!($form_state['values']['amount']>0)) {
	    form_set_error('amount', '请输入正数');
	  } 
}

function managerialoutput_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['managerialoutput_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 //$form_state['redirect'] = 'fundmanage/managerialoutput/confirm';
	   /**
	   * 写入数据库
	   */
	   
	$values = NULL;
    //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	if(empty($_SESSION['managerialoutput_form'])){
	 //drupal_goto('contact');
		$form_state['redirect'] = 'fundmanage/managerialoutput/create';
	}else{
		$values = $_SESSION['managerialoutput_form'];
		unset($_SESSION['managerialoutput_form']);
    }
	  
	$fid = $form_state['values']['upload']; 
	$file = file_load($fid);  
	
	if ($file != null) {
		$filename = $values['file_name'];
		if($filename == "")
			$filename = "附件";
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
		  
	      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('managerial_output')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'url' => $saveurl,
		   		 'file_name' => $filename,	 
			     'file_managed_id' => $fid,
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/managerialoutput/list/'.$last_id;
			 $form_state['redirect'] = 'fundmanage/managerialoutput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	  } 
	  else {
		  form_set_error('upload',$extension_errors[0]); 
	  }
	}
	else{
		$datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('managerial_output')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/managerialoutput/list/'.$last_id;
			  $form_state['redirect'] = 'fundmanage/managerialoutput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	}
}
 
function managerialoutput_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/managerialoutput/create';
}

function managerialoutput_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['managerialoutput_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/managerialoutput/create';
	  }else{
		  $values = $_SESSION['managerialoutput_form'];
		  unset($_SESSION['managerialoutput_form']);
	  }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('managerial_output')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		  //$form_state['redirect'] = 'fundmanage/managerialoutput/list/'.$last_id;
		  $form_state['redirect'] = 'fundmanage/managerialoutput/list';
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function managerialoutput_edit_form($form, &$form_state, $perid){
  $query = "SELECT serial_number,amount,timestamp,remark, file_name, url, file_managed_id FROM " .
           "{managerial_output} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	$datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
	$amount = $links->amount;
    $remark = $links->remark;
	$file_name =  $links->file_name;
	$url =  $links->url;
	$file_managed_id = $links->file_managed_id;
	//$page_content = str_replace(array("\n", "\r\n") , "<br />", $page_content);
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id); 
   $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['managerialoutput_edit_form']['serial_number'])?$_SESSION['managerialoutput_edit_form']['serial_number']:$serial_number,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('支出资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['managerialoutput_edit_form']['amount'])?$_SESSION['managerialoutput_edit_form']['amount']:$amount,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('支出时间'),
	     '#default_value' => isset($_SESSION['managerialoutput_edit_form']['timestamp'])?$_SESSION['managerialoutput_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['managerialoutput_edit_form']['remark'])?$_SESSION['managerialoutput_edit_form']['remark']:$remark,
	 );
	 
	$form['file_name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => FAlSE,
	  '#default_value' =>isset($_SESSION['managerialoutput_edit_form']['file_name'])?$_SESSION['managerialoutput_edit_form']['file_name']:$file_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交附件',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(50*1024*1024)),
	 );
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    //'#value' => t('删除该管理费支出记录'),
	    '#value' => t('删除该记录'),
	    '#submit' => array('managerialoutput_edit_form_deleate'),
	  );
  }
 
  return $form;
}

function managerialoutput_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	 
	 $fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	$filename = $values['file_name'];
	if($filename == "")
		$filename = "附件";
	$filemanagedid = $values['file_managed_id'];
	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}
			  db_update('managerial_output')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
				   	 'url' => $saveurl,
				   	 'file_managed_id' => $fid,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 	 //$form_state['redirect'] = 'fundmanage/managerialoutput/list/'.$values['bid'];
				 $form_state['redirect'] = 'fundmanage/managerialoutput/list';
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		 db_update('managerial_output')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
   			 'file_name' => $filename,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 //$form_state['redirect'] = 'fundmanage/managerialoutput/list/'.$values['bid'];
	 $form_state['redirect'] = 'fundmanage/managerialoutput/list';
	}
}

function managerialoutput_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['managerialoutput_edit_form'] = $form_state['values'];
	 $values = $_SESSION['managerialoutput_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/managerialoutput/deleate/'.$values['bid'];
}

function managerialoutput_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该管理费支出记录将不可恢复！';
  
  drupal_set_title('删除该管理费支出记录');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('managerialoutput_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function managerialoutput_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('managerialoutput_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function managerialoutput_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['managerialoutput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/managerialoutput/list';
	  }else{
		  $values = $_SESSION['managerialoutput_edit_form'];
		  unset($_SESSION['managerialoutput_edit_form']);
		  $form_state['redirect'] = 'fundmanage/managerialoutput/list/'.$values['bid'];
	  }
}

function managerialoutput_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['managerialoutput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/managerialoutput/list';
	  }else{
		  $values = $_SESSION['managerialoutput_edit_form'];
		  unset($_SESSION['managerialoutput_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('managerial_output')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'fundmanage/managerialoutput/list';;
	  }

}


/**
 *财政资金支出
 */
function financeoutput_create(){
	  //我们为这个页面设置标题
	 drupal_set_title('新增财政资金支出');
	 $page_content = l('查看财政资金支出记录','fundmanage/financeoutput/list') . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('financeoutput_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function financeoutput_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增财政资金支出');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['financeoutput_form'])){
	  drupal_goto('fundmanage/profitinput/create');
	 }else{
	 }
	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('financeoutput_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function financeoutput_exportcsv_page(){
  $filename = '财政资金支出.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','支出时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('finance_output', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }  
}

function financeoutput_list_page() {
 
  //$html = l('添加财政资金支出','fundmanage/financeoutput/create') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
	  $html = l('添加记录','fundmanage/financeoutput/create') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/financeoutput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '支出时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '附件', 'field' => 'file'),
      array('data' => '更多附件管理', 'field' => 'file_list'),
      );
  $query = db_select('finance_output', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
       'file_name',
       'url',
      ));
  $results = $query
      ->execute();

  $rows = array();
  $perlink = '';

  foreach ($results as $node) {	
  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/financeoutput/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
	  $filelink = '';
  	  if($node->file_name!='')
	  	$filelink = l($node->file_name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$node->url);
      $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        $filelink,
         l('附件列表管理', 'jilu_file/create/jiluid/'.$node->id)
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有财政资金支出记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function financeoutput_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看财政资金支出记录','fundmanage/financeoutput/list') . '<br />'. '<br />';
 
  drupal_set_title('管理该项财政资金支出记录');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('financeoutput_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function financeoutput_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['financeoutput_form']['serial_number'])?$_SESSION['financeoutput_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('支出资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['financeoutput_form']['amount'])?$_SESSION['financeoutput_form']['amount']:"",
 );
 $datetime = $_SESSION['financeoutput_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('支出时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['financeoutput_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['financeoutput_form']['remark'])?$_SESSION['financeoutput_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('financeoutput_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function financeoutput_form(){
	  //添加我们自己的CSS，用来控制表单的样式
	 //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
	 $count_serialnum = 1;
	 $query = db_select('finance_output', 'n') 
      ->fields ('n', array (
      'id',
      'serial_number',
      ));
	  $results = $query
	      ->execute();
    $maxno = 0;
    foreach ($results as $node) {
        $ser_num = intval(substr($node->serial_number, 4, 4));
        if ($ser_num > $maxno) $maxno = $ser_num;
    }
    $count_serialnum = $maxno + 1;
     if($count_serialnum<10)
	 	$count_serialnum = '000'.$count_serialnum;
	 elseif ($count_serialnum<100) {
		$count_serialnum = '00'.$count_serialnum; 
	 }
	 elseif ($count_serialnum<1000) {
		$count_serialnum = '0'.$count_serialnum; 
	 }
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['financeoutput_form']['serial_number'])?$_SESSION['financeoutput_form']['serial_number']:"czhc".$count_serialnum,
	  //'#description' => t('例如：czzc01'),
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('支出资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['financeoutput_form']['amount'])?$_SESSION['financeoutput_form']['amount']:"",
	  '#description' => t('例如：250.55'),
	 );
	 
	 $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('支出时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['financeoutput_form']['remark'])?$_SESSION['financeoutput_form']['remark']:"",
	 );
	 
	 $form['upload'] = array(
	   '#type' => 'managed_file',
	   '#title' => '附件上传',
	   '#required' => FALSE,
	   '#upload_location' => 'public://my_uploads',
	   '#upload_validators' => array(
	     'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		 'file_validate_size' => array(50*1024*1024)),
	 );
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => FALSE,
	  '#default_value' =>"附件",
	 );	
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function financeoutput_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['amount']) > 10) {
	    form_set_error('amount', '要求精度小于10 个字符');
	  } 
	  if (!($form_state['values']['amount']>0)) {
	    form_set_error('amount', '请输入正数');
	  } 
}

function financeoutput_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['financeoutput_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 //$form_state['redirect'] = 'fundmanage/financeoutput/confirm';
	  /**
	   * 写入数据库
	   */
	   
	$values = NULL;
    //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	if(empty($_SESSION['financeoutput_form'])){
	 //drupal_goto('contact');
		$form_state['redirect'] = 'fundmanage/financeoutput/create';
	}else{
		$values = $_SESSION['financeoutput_form'];
		unset($_SESSION['financeoutput_form']);
    }
	  
	$fid = $form_state['values']['upload']; 
	$file = file_load($fid);  
	
	if ($file != null) {
		$filename = $values['file_name'];
		if($filename == "")
			$filename = "附件";
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
		  
	      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('finance_output')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'url' => $saveurl,
		   		 'file_name' => $filename,	 
			     'file_managed_id' => $fid,
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/financeoutput/list/'.$last_id;
			  $form_state['redirect'] = 'fundmanage/financeoutput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	  } 
	  else {
		  form_set_error('upload',$extension_errors[0]); 
	  }
	}
	else{
		$datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('finance_output')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	  			))->execute();
		  if ($last_id!=NULL) {
			  //$form_state['redirect'] = 'fundmanage/financeoutput/list/'.$last_id;
			  $form_state['redirect'] = 'fundmanage/financeoutput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	}
}
 
function financeoutput_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/financeoutput/create';
}

function financeoutput_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['financeoutput_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/financeoutput/create';
	  }else{
		  $values = $_SESSION['financeoutput_form'];
		  unset($_SESSION['financeoutput_form']);
	  }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('finance_output')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		 //$form_state['redirect'] = 'fundmanage/financeoutput/list/'.$last_id;
		  $form_state['redirect'] = 'fundmanage/financeoutput/list';
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function financeoutput_edit_form($form, &$form_state, $perid){
  $query = "SELECT serial_number,amount,timestamp,remark, file_name, url, file_managed_id FROM " .
           "{finance_output} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	$datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
	$amount = $links->amount;
    $remark = $links->remark;
	$file_name =  $links->file_name;
	$url =  $links->url;
	$file_managed_id = $links->file_managed_id;
	//$page_content = str_replace(array("\n", "\r\n") , "<br />", $page_content);
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id); 
   $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['financeoutput_edit_form']['serial_number'])?$_SESSION['financeoutput_edit_form']['serial_number']:$serial_number,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('支出资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['financeoutput_edit_form']['amount'])?$_SESSION['financeoutput_edit_form']['amount']:$amount,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('支出时间'),
	     '#default_value' => isset($_SESSION['financeoutput_edit_form']['timestamp'])?$_SESSION['financeoutput_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['financeoutput_edit_form']['remark'])?$_SESSION['financeoutput_edit_form']['remark']:$remark,
	 );
	
	$form['file_name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => FAlSE,
	  '#default_value' =>isset($_SESSION['financeoutput_edit_form']['file_name'])?$_SESSION['financeoutput_edit_form']['file_name']:$file_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交附件',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(50*1024*1024)),
	 );
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    //'#value' => t('删除该财政资金支出记录'),
	    '#value' => t('删除该记录'),
	    '#submit' => array('financeoutput_edit_form_deleate'),
	  );
  }
 
  return $form;
}

function financeoutput_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  
	 
	  $fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	$filename = $values['file_name'];
	if($filename == "")
		$filename = "附件";
	$filemanagedid = $values['file_managed_id'];
	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}
			  db_update('finance_output')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
				   	 'url' => $saveurl,
				   	 'file_managed_id' => $fid,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 	 //$form_state['redirect'] = 'fundmanage/financeoutput/list/'.$values['bid'];
				 $form_state['redirect'] = 'fundmanage/financeoutput/list';
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('finance_output')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
   			 'file_name' => $filename,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 //$form_state['redirect'] = 'fundmanage/financeoutput/list/'.$values['bid'];
	 $form_state['redirect'] = 'fundmanage/financeoutput/list';
	}
}

function financeoutput_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['financeoutput_edit_form'] = $form_state['values'];
	 $values = $_SESSION['financeoutput_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/financeoutput/deleate/'.$values['bid'];
}

function financeoutput_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该财政资金支出记录将不可恢复！';
  
  drupal_set_title('删除该财政资金支出记录');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('financeoutput_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function financeoutput_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('financeoutput_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function financeoutput_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['financeoutput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/financeoutput/list';
	  }else{
		  $values = $_SESSION['financeoutput_edit_form'];
		  unset($_SESSION['financeoutput_edit_form']);
		  $form_state['redirect'] = 'fundmanage/financeoutput/list/'.$values['bid'];
	  }
}

function financeoutput_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['financeoutput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/financeoutput/list';
	  }else{
		  $values = $_SESSION['financeoutput_edit_form'];
		  unset($_SESSION['financeoutput_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('finance_output')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'fundmanage/financeoutput/list';;
	  }

}



/**
 *其他支出
 */
function otheroutput_create(){
	  //我们为这个页面设置标题
	 drupal_set_title('新增其他支出');
	 $page_content = l('查看其他支出记录','fundmanage/otheroutput/list') . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('otheroutput_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function otheroutput_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增其他支出');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['otheroutput_form'])){
	  drupal_goto('fundmanage/profitinput/create');
	 }else{
	 }
	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('otheroutput_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function otheroutput_exportcsv_page(){
  $filename = '其他支出.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','支出时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('other_output', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }  
}

function otheroutput_list_page() {
 
  //$html = l('添加其他支出','fundmanage/otheroutput/create')  .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
	  $html = l('添加记录','fundmanage/otheroutput/create')  .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/otheroutput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '支出时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '附件', 'field' => 'file'),
      array('data' => '更多附件管理', 'field' => 'file_list'),
      );
  $query = db_select('other_output', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
       'file_name',
       'url',
      ));
  $results = $query
      ->execute();

  $rows = array();
  $perlink = '';
  foreach ($results as $node) {
  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/otheroutput/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
	  $filelink = '';
  	  if($node->file_name!='')
	  	$filelink = l($node->file_name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$node->url);
      $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        $filelink,
         l('附件列表管理', 'jilu_file/create/jiluid/'.$node->id)
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有其他支出记录',//Optional empty text for the table if resultset is empty
      )
      ); 
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function otheroutput_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看其他支出记录','fundmanage/otheroutput/list') . '<br />'. '<br />';
  
  drupal_set_title('管理该项其他支出记录');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('otheroutput_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function otheroutput_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['otheroutput_form']['serial_number'])?$_SESSION['otheroutput_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('支出资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['otheroutput_form']['amount'])?$_SESSION['otheroutput_form']['amount']:"",
 );
 $datetime = $_SESSION['otheroutput_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('支出时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['otheroutput_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['otheroutput_form']['remark'])?$_SESSION['otheroutput_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('otheroutput_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function otheroutput_form(){
	  //添加我们自己的CSS，用来控制表单的样式
	 //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
	 $count_serialnum = 1;
	 $query = db_select('other_output', 'n') 
      ->fields ('n', array (
      'id',
      'serial_number',
      ));
	  $results = $query
	      ->execute();
    $maxno = 0;
    foreach ($results as $node) {
        $ser_num = intval(substr($node->serial_number, 4, 4));
        if ($ser_num > $maxno) $maxno = $ser_num;
    }
    $count_serialnum = $maxno + 1;
     if($count_serialnum<10)
	 	$count_serialnum = '000'.$count_serialnum;
	 elseif ($count_serialnum<100) {
		$count_serialnum = '00'.$count_serialnum; 
	 }
	 elseif ($count_serialnum<1000) {
		$count_serialnum = '0'.$count_serialnum; 
	 }
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['otheroutput_form']['serial_number'])?$_SESSION['otheroutput_form']['serial_number']:"qtzc".$count_serialnum,
	  //'#description' => t('例如：qtzc01'),
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('支出资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['otheroutput_form']['amount'])?$_SESSION['otheroutput_form']['amount']:"",
	  '#description' => t('例如：250.55'),
	 );
	 
	 $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('支出时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['otheroutput_form']['remark'])?$_SESSION['otheroutput_form']['remark']:"",
	 );
	
	$form['upload'] = array(
	   '#type' => 'managed_file',
	   '#title' => '附件上传',
	   '#required' => FALSE,
	   '#upload_location' => 'public://my_uploads',
	   '#upload_validators' => array(
	     'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		 'file_validate_size' => array(50*1024*1024)),
	 );
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => FALSE,
	  '#default_value' =>"附件",
	 );	
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function otheroutput_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['amount']) > 10) {
	    form_set_error('amount', '要求精度小于10 个字符');
	  } 
	  if (!($form_state['values']['amount']>0)) {
	    form_set_error('amount', '请输入正数');
	  } 
}

function otheroutput_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['otheroutput_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 //$form_state['redirect'] = 'fundmanage/otheroutput/confirm';
	  /**
	   * 写入数据库
	   */
	   
	$values = NULL;
    //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	if(empty($_SESSION['otheroutput_form'])){
	 //drupal_goto('contact');
		$form_state['redirect'] = 'fundmanage/otheroutput/create';
	}else{
		$values = $_SESSION['otheroutput_form'];
		unset($_SESSION['otheroutput_form']);
    }
	  
	$fid = $form_state['values']['upload']; 
	$file = file_load($fid);  
	
	if ($file != null) {
		$filename = $values['file_name'];
		if($filename == "")
			$filename = "附件";
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
		  
	      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('other_output')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	   			 'url' => $saveurl,
		   		 'file_name' => $filename,	 
			     'file_managed_id' => $fid,
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/otheroutput/list/'.$last_id;
			 $form_state['redirect'] = 'fundmanage/otheroutput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	  } 
	  else {
		  form_set_error('upload',$extension_errors[0]); 
	  }
	}
	else{
		$datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
		  $last_id = db_insert('other_output')
	  		->fields(array(
	   			 'serial_number' => $values['serial_number'],
	   			 'amount' => $values['amount'],
	   			 'timestamp' =>  $datetime,
	   			 'remark' => $values['remark'],
	  			))->execute();
		  if ($last_id!=NULL) {
			 //$form_state['redirect'] = 'fundmanage/otheroutput/list/'.$last_id;
			  $form_state['redirect'] = 'fundmanage/otheroutput/list';
		  } else {		    
		    // 数据写入失败了
		    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');		    
		  }	
	}
}
 
function otheroutput_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/otheroutput/create';
}

function otheroutput_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['otheroutput_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/otheroutput/create';
	  }else{
		  $values = $_SESSION['otheroutput_form'];
		  unset($_SESSION['otheroutput_form']);
	  }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('other_output')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		  //$form_state['redirect'] = 'fundmanage/otheroutput/list/'.$last_id;
		  $form_state['redirect'] = 'fundmanage/otheroutput/list';
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function otheroutput_edit_form($form, &$form_state, $perid){
  $query = "SELECT serial_number,amount,timestamp,remark, file_name, url, file_managed_id FROM " .
           "{other_output} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	$datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
	$amount = $links->amount;
    $remark = $links->remark;
	$file_name =  $links->file_name;
	$url =  $links->url;
	$file_managed_id = $links->file_managed_id;
	//$page_content = str_replace(array("\n", "\r\n") , "<br />", $page_content);
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id); 
   $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['otheroutput_edit_form']['serial_number'])?$_SESSION['otheroutput_edit_form']['serial_number']:$serial_number,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('支出资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['otheroutput_edit_form']['amount'])?$_SESSION['otheroutput_edit_form']['amount']:$amount,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('支出时间'),
	     '#default_value' => isset($_SESSION['otheroutput_edit_form']['timestamp'])?$_SESSION['otheroutput_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['otheroutput_edit_form']['remark'])?$_SESSION['otheroutput_edit_form']['remark']:$remark,
	 );
	 
	 $form['file_name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => FAlSE,
	  '#default_value' =>isset($_SESSION['otheroutput_edit_form']['file_name'])?$_SESSION['otheroutput_edit_form']['file_name']:$file_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交附件',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(50*1024*1024)),
	 );
	 
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    //'#value' => t('删除该其他支出记录'),
	    '#value' => t('删除该记录'),
	    '#submit' => array('otheroutput_edit_form_deleate'),
	  );
  }
  
  return $form;
}

function otheroutput_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  
	 
	 $fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	$filename = $values['file_name'];
	if($filename == "")
		$filename = "附件";
	$filemanagedid = $values['file_managed_id'];
	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}
			  db_update('other_output')
		  		->fields(array(
		   			 'serial_number' => $values['serial_number'],
		   			 'amount' => $values['amount'],
		   			 'timestamp' =>  $datetime,
		   			 'remark' => $values['remark'],
		   			 'file_name' => $filename,
				   	 'url' => $saveurl,
				   	 'file_managed_id' => $fid,
		  			))
		  		->condition('id', $values['bid'])
		  		->execute();
			 	 //$form_state['redirect'] = 'fundmanage/otheroutput/list/'.$values['bid'];
				 $form_state['redirect'] = 'fundmanage/otheroutput/list';
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('other_output')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
   			 'file_name' => $filename,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 //$form_state['redirect'] = 'fundmanage/otheroutput/list/'.$values['bid'];
	 $form_state['redirect'] = 'fundmanage/otheroutput/list';
	}
}

function otheroutput_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['otheroutput_edit_form'] = $form_state['values'];
	 $values = $_SESSION['otheroutput_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/otheroutput/deleate/'.$values['bid'];
}

function otheroutput_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该其他支出记录将不可恢复！';
  
  drupal_set_title('删除该其他支出记录');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('otheroutput_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function otheroutput_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('otheroutput_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function otheroutput_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['otheroutput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/otheroutput/list';
	  }else{
		  $values = $_SESSION['otheroutput_edit_form'];
		  unset($_SESSION['otheroutput_edit_form']);
		  $form_state['redirect'] = 'fundmanage/otheroutput/list/'.$values['bid'];
	  }
}

function otheroutput_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['otheroutput_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/otheroutput/list';
	  }else{
		  $values = $_SESSION['otheroutput_edit_form'];
		  unset($_SESSION['otheroutput_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('other_output')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'fundmanage/otheroutput/list';;
	  }

}

/**
 *浮动盈亏
 */
function fudong_yingkui_create(){
	  //我们为这个页面设置标题
	 drupal_set_title('新增浮动盈亏');
	 $page_content = l('查看浮动盈亏记录','fundmanage/fudong_yingkui/list') . '<br />'. '<br />';
	 $render_array = array(
	   '#markup' => $page_content, 
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('fudong_yingkui_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function fudong_yingkui_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('新增浮动盈亏');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['fudong_yingkui_form'])){
	  drupal_goto('fundmanage/profitinput/create');
	 }else{
	 }
	
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('fudong_yingkui_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function fudong_yingkui_exportcsv_page(){
  $filename = '浮动盈亏.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','编号'),
       iconv('utf-8','gb2312','金额（元）'),
       iconv('utf-8','gb2312','录入时间'),
       iconv('utf-8','gb2312', '备注'),
      );
  print implode(',', $header) ."\r\n";
  $query = db_select('fudong_yingkui', 'n')
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();
    foreach ($results as $node) {
      $datetime = str_replace(array(',',",",'，',"，") , " ", format_date($node->timestamp, 'custom', 'Y-m-d'));
      $values = array($node->serial_number,$node->amount,$datetime,$node->remark); 
	  $str = implode(',', $values) ."\r\n";
	  $str = iconv('utf-8','gb2312',$str);
	  print $str;
    }  
}

function fudong_yingkui_list_page() {
 
  //$html = l('添加浮动盈亏','fundmanage/fudong_yingkui/create')  .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = '';
  if(user_access('manage fund'))
	  $html = l('添加记录','fundmanage/fudong_yingkui/create')  .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','fundmanage/fudong_yingkui/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  $header = array(
      array('data' => '编号', 'field' => 'serial_number',),
      array('data' => '金额（元）', 'field' => 'amount'),
      array('data' => '录入时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      );
  $query = db_select('fudong_yingkui', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'serial_number',
      'amount',
      'timestamp',
       'remark',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  	  if(user_access('manage fund'))
	  	$perlink = l($node->serial_number, 'fundmanage/fudong_yingkui/list/'. $node->id);
	  else 
	  	$perlink = $node->serial_number;
      $amount=number_format($node->amount, 2, '.', ','); 
      $rows[] = array(
      'data' => array(
        $perlink,
        $amount,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有浮动盈亏记录',//Optional empty text for the table if resultset is empty
      )
      ); 
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function fudong_yingkui_per_page($perid) {
 
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看浮动盈亏记录','fundmanage/fudong_yingkui/list') . '<br />'. '<br />';
  
  drupal_set_title('管理该项浮动盈亏记录');
	 
  $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $form = drupal_get_form('fudong_yingkui_edit_form',$perid);
  $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;
}

function fudong_yingkui_confirm_form(){

 //drupal_set_message(print_r($_SESSION['contactus_form']));
 //表单元素“姓名”
 $form['serial_number'] = array(
  '#title' => t('编号'),
  //表单元素的类型,这里为item
  '#type' => 'item',
  '#markup' => isset($_SESSION['fudong_yingkui_form']['serial_number'])?$_SESSION['fudong_yingkui_form']['serial_number']:"",
 );
 
  //表单元素“单位名称”
 $form['amount'] = array(
  '#title' => t('录入资金金额（单位：元）'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['fudong_yingkui_form']['amount'])?$_SESSION['fudong_yingkui_form']['amount']:"",
 );
 $datetime = $_SESSION['fudong_yingkui_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('录入时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['fudong_yingkui_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
  //表单元素“邮件正文”
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['fudong_yingkui_form']['remark'])?$_SESSION['fudong_yingkui_form']['remark']:"",
 );

 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('fudong_yingkui_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function fudong_yingkui_form(){
	  //添加我们自己的CSS，用来控制表单的样式
	 //drupal_add_css(drupal_get_path('module', 'contactus').'/contactus.css');
	 
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fudong_yingkui_form']['serial_number'])?$_SESSION['fudong_yingkui_form']['serial_number']:"",
	  '#description' => t('例如：fdyk01'),
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('录入资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fudong_yingkui_form']['amount'])?$_SESSION['fudong_yingkui_form']['amount']:"",
	  '#description' => t('例如：(-)250.55'),
	 );
	 
	 $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('录入时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['fudong_yingkui_form']['remark'])?$_SESSION['fudong_yingkui_form']['remark']:"",
	 );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	  );
	  return $form;
}

function fudong_yingkui_form_validate($form, &$form_state){
	  if (drupal_strlen($form_state['values']['amount']) > 10) {
	    form_set_error('amount', '要求精度小于10 个字符');
	  } 
	  if (!($form_state['values']['amount']>0||$form_state['values']['amount']<0)) {
	    form_set_error('amount', '请填写数字（负数可在数字前加“-”号）');
	  } 
}

function fudong_yingkui_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['fudong_yingkui_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/fudong_yingkui/confirm';
}
 
function fudong_yingkui_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'fundmanage/fudong_yingkui/create';
}

function fudong_yingkui_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['fudong_yingkui_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/fudong_yingkui/create';
	  }else{
		  $values = $_SESSION['fudong_yingkui_form'];
		  unset($_SESSION['fudong_yingkui_form']);
	  }
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('fudong_yingkui')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))->execute();
	  if ($last_id!=NULL) {
		 $form_state['redirect'] = 'fundmanage/fudong_yingkui/list/'.$last_id;
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }	
}

function fudong_yingkui_edit_form($form, &$form_state, $perid){
  $query = "SELECT serial_number,amount,timestamp,remark FROM " .
           "{fudong_yingkui} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	$datetime = getdate($links->timestamp);
    $serial_number = $links->serial_number;
	$amount = $links->amount;
    $remark = $links->remark;
	//$page_content = str_replace(array("\n", "\r\n") , "<br />", $page_content);
  }
  // More coming....
  if ($queryResult == '') {
    $form = NULL;
  }
  else{
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['serial_number'] = array(
	  '#title' => t('编号'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fudong_yingkui_edit_form']['serial_number'])?$_SESSION['fudong_yingkui_edit_form']['serial_number']:$serial_number,
	 );
	 
	 $form['amount'] = array(
	  '#title' => t('录入资金金额（单位：元）'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fudong_yingkui_edit_form']['amount'])?$_SESSION['fudong_yingkui_edit_form']['amount']:$amount,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('录入时间'),
	     '#default_value' => isset($_SESSION['fudong_yingkui_edit_form']['timestamp'])?$_SESSION['fudong_yingkui_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
  	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['fudong_yingkui_edit_form']['remark'])?$_SESSION['fudong_yingkui_edit_form']['remark']:$remark,
	 );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    //'#value' => t('删除该浮动盈亏记录'),
	    '#value' => t('删除该记录'),
	    '#submit' => array('fudong_yingkui_edit_form_deleate'),
	  );
  }
  
  return $form;
}

function fudong_yingkui_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];
      $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  db_update('fudong_yingkui')
  		->fields(array(
   			 'serial_number' => $values['serial_number'],
   			 'amount' => $values['amount'],
   			 'timestamp' =>  $datetime,
   			 'remark' => $values['remark'],
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'fundmanage/fudong_yingkui/list/'.$values['bid'];
}

function fudong_yingkui_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['fudong_yingkui_edit_form'] = $form_state['values'];
	 $values = $_SESSION['fudong_yingkui_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fundmanage/fudong_yingkui/deleate/'.$values['bid'];
}

function fudong_yingkui_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该浮动盈亏记录将不可恢复！';
  
  drupal_set_title('删除该浮动盈亏记录');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('fudong_yingkui_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function fudong_yingkui_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('fudong_yingkui_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function fudong_yingkui_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['fudong_yingkui_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/fudong_yingkui/list';
	  }else{
		  $values = $_SESSION['fudong_yingkui_edit_form'];
		  unset($_SESSION['fudong_yingkui_edit_form']);
		  $form_state['redirect'] = 'fundmanage/fudong_yingkui/list/'.$values['bid'];
	  }
}

function fudong_yingkui_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['fudong_yingkui_edit_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'fundmanage/fudong_yingkui/list';
	  }else{
		  $values = $_SESSION['fudong_yingkui_edit_form'];
		  unset($_SESSION['fudong_yingkui_edit_form']);
		  db_delete('fudong_yingkui')
			->condition('id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'fundmanage/fudong_yingkui/list';;
	  }

}

////////
//汇总记录
///////
function allinput_exportcsv_page(){
  $filename = '收入明细.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','财政资金划入(元)'),
       iconv('utf-8','gb2312','参股基金收入(元)'),
       iconv('utf-8','gb2312','利息收入(元)'),
       iconv('utf-8','gb2312','其他收入(元)'),
       iconv('utf-8','gb2312', '总收入(元)'),
      );
  print implode(',', $header) ."\r\n";
 $financeinput = 0;
  $profitinput = 0;
  $interestinput = 0;
  $otherinput = 0;
  $allinput = 0;
  
  $query = db_select('finance_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$financeinput+=$node->amount;
  }
  
  $query = db_select('profit_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$profitinput+=$node->amount;
  }

  $query = db_select('interest_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
    $interestinput+=$node->amount;
  }

  $query = db_select('other_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$otherinput+=$node->amount;
  }
  
  $allinput += $financeinput;
  $allinput += $profitinput;
  $allinput += $interestinput;
  $allinput += $otherinput;
  $values = array($financeinput,$profitinput,$interestinput,$otherinput,$allinput);
  $str = implode(',', $values) ."\r\n";
  $str = iconv('utf-8','gb2312',$str);
  print $str;
}

function allinput_list_page() {
 
  //$html = l('财政资金划入记录','fundmanage/financeinput/list') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  //$html .= l('参股基金收入记录','fundmanage/profitinput/list') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  //$html .= l('利息收入记录','fundmanage/interestinput/list') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  //$html .= l('其他收入记录','fundmanage/otherinput/list') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = l('导出','fundmanage/allinput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  
  $header = array(
      array('data' => '财政资金划入(元)', 'field' => 'financeinput',),
      array('data' => '参股基金收入(元)', 'field' => 'profitinput'),
      array('data' => '利息收入(元)', 'field' => 'interestinput'),
      array('data' => '其他收入(元)', 'field' => 'otherinput'),
      array('data' => '总收入(元)', 'field' => 'allinput'),
      );
  $financeinput = 0;
  $profitinput = 0;
  $interestinput = 0;
  $otherinput = 0;
  $allinput = 0;
  
  $query = db_select('finance_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$financeinput+=$node->amount;
  }
  
  $query = db_select('profit_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$profitinput+=$node->amount;
  }

  $query = db_select('interest_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
    $interestinput+=$node->amount;
  }
  
  $query = db_select('other_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$otherinput+=$node->amount;
  }
  
  $allinput += $financeinput;
  $allinput += $profitinput;
  $allinput += $interestinput;
  $allinput += $otherinput;
  $financeinput=number_format($financeinput, 2, '.', ','); 
  $profitinput=number_format($profitinput, 2, '.', ','); 
  $interestinput=number_format($interestinput, 2, '.', ','); 
  $otherinput=number_format($otherinput, 2, '.', ','); 
  $allinput=number_format($allinput, 2, '.', ','); 
  $rows[] = array(
      'data' => array(
        l($financeinput,'fundmanage/financeinput/list'),
        l($profitinput,'fundmanage/profitinput/list'),
        l($interestinput,'fundmanage/interestinput/list'),
        l($otherinput,'fundmanage/otherinput/list'),
        $allinput,
      )
  );
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有收入记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';

  return ($html); 
}

function alloutput_exportcsv_page(){
  $filename = '支出明细.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
       iconv('utf-8','gb2312','基金参股支出(元)'),
       iconv('utf-8','gb2312','管理费划出(元)'),
       iconv('utf-8','gb2312','财政资金支出(元)'),
       iconv('utf-8','gb2312', '其他支出(元)'),
       iconv('utf-8','gb2312', '总支出(元)'),
      );
  print implode(',', $header) ."\r\n";
  
 $stockoutput = 0;
  $managerialoutput = 0;
  $financeoutput = 0;
  $otheroutput = 0;
  $alloutput =0;
  
  $query = db_select('stock_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$stockoutput+=$node->amount;
  }
  
  $query = db_select('managerial_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$managerialoutput+=$node->amount;
  }
  
  $query = db_select('finance_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$financeoutput+=$node->amount;
  }
  
  $query = db_select('other_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$otheroutput+=$node->amount;
  }
  $alloutput += $stockoutput;
  $alloutput += $managerialoutput;
  $alloutput += $financeoutput;
  $alloutput += $otheroutput;
  
  $values = array($stockoutput,$managerialoutput,$financeoutput,$otheroutput,$alloutput);
  $str = implode(',', $values) ."\r\n";
  $str = iconv('utf-8','gb2312',$str);
  print $str;
}

function alloutput_list_page() {
 
  //$html = l('基金参股支出记录','fundmanage/stockoutput/list') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  //$html .= l('管理费划出记录','fundmanage/managerialoutput/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  //$html .= l('财政资金支出记录','fundmanage/financeoutput/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  //$html .= l('其他支出记录','fundmanage/otheroutput/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html = l('导出','fundmanage/alloutput/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  
  $header = array(
      array('data' => '基金参股支出(元)', 'field' => 'stockoutput',),
      array('data' => '管理费划出(元)', 'field' => 'managerialoutput'),
      array('data' => '财政资金支出(元)', 'field' => 'financeoutput'),
      array('data' => '其他支出(元)', 'field' => 'otheroutput'),
      array('data' => '总支出(元)', 'field' => 'alloutput'),
      );
  $stockoutput = 0;
  $managerialoutput = 0;
  $financeoutput = 0;
  $otheroutput = 0;
  $alloutput =0;
  
  $query = db_select('stock_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$stockoutput+=$node->amount;
  }
  
  $query = db_select('managerial_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$managerialoutput+=$node->amount;
  }
  
  $query = db_select('finance_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$financeoutput+=$node->amount;
  }
  
  $query = db_select('other_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$otheroutput+=$node->amount;
  }
  $alloutput += $stockoutput;
  $alloutput += $managerialoutput;
  $alloutput += $financeoutput;
  $alloutput += $otheroutput;
  $stockoutput=number_format($stockoutput, 2, '.', ','); 
  $managerialoutput=number_format($managerialoutput, 2, '.', ','); 
  $financeoutput=number_format($financeoutput, 2, '.', ','); 
  $otheroutput=number_format($otheroutput, 2, '.', ','); 
  $alloutput=number_format($alloutput, 2, '.', ','); 
  $rows[] = array(
      'data' => array(
        l($stockoutput,'fundmanage/stockoutput/list'),
        l($managerialoutput,'fundmanage/managerialoutput/list'),
        l($financeoutput,'fundmanage/financeoutput/list'),
        l($otheroutput,'fundmanage/otheroutput/list'),
        $alloutput,
      )
  );
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有支出记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  return ($html); 
}

function statistics_exportcsv_page(){
  $filename = '汇总明细.csv' ;
  drupal_add_http_header('Content-Type', 'text/csv; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $header = array(
 	   iconv('utf-8','gb2312','财政资金划入(元)'),
       iconv('utf-8','gb2312','参股基金收入(元)'),
       iconv('utf-8','gb2312','利息收入(元)'),
       iconv('utf-8','gb2312','其他收入(元)'),
       iconv('utf-8','gb2312', '总收入(元)'),
       iconv('utf-8','gb2312','基金参股支出(元)'),
       iconv('utf-8','gb2312','管理费划出(元)'),
       iconv('utf-8','gb2312','财政资金支出(元)'),
       iconv('utf-8','gb2312', '其他支出(元)'),
       iconv('utf-8','gb2312', '总支出(元)'),
       iconv('utf-8','gb2312', '浮动盈亏(元)'),
       iconv('utf-8','gb2312', '资金余额(元)'),
      );
  print implode(',', $header) ."\r\n";
  
  $financeinput = 0;
  $profitinput = 0;
  $interestinput = 0;
  $otherinput = 0;
  $allinput = 0;
  
  $query = db_select('finance_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$financeinput+=$node->amount;
  }
  
  $query = db_select('profit_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$profitinput+=$node->amount;
  }

  $query = db_select('interest_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
    $interestinput+=$node->amount;
  }

  $query = db_select('other_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$otherinput+=$node->amount;
  }
  
  $allinput += $financeinput;
  $allinput += $profitinput;
  $allinput += $interestinput;
  $allinput += $otherinput;
 $stockoutput = 0;
  $managerialoutput = 0;
  $financeoutput = 0;
  $otheroutput = 0;
  $alloutput =0;
  
  $query = db_select('stock_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$stockoutput+=$node->amount;
  }
  
  $query = db_select('managerial_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$managerialoutput+=$node->amount;
  }
  
  $query = db_select('finance_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$financeoutput+=$node->amount;
  }
  
  $query = db_select('other_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$otheroutput+=$node->amount;
  }
  $alloutput += $stockoutput;
  $alloutput += $managerialoutput;
  $alloutput += $financeoutput;
  $alloutput += $otheroutput;
  
  $values = array( $financeinput,$profitinput,$interestinput,$otherinput,$allinput,
  	$stockoutput,$managerialoutput,$financeoutput,$otheroutput,$alloutput,0,$allinput-$alloutput);
  $str = implode(',', $values) ."\r\n";
  $str = iconv('utf-8','gb2312',$str);
  print $str;
}

function statistics_page() {
 
  $html = "";
  $html .= l('导出','fundmanage/statistics/exportcsv') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  );

  $html .= area_print_form($options). '<br />'. '<br />';  
  $html .= '<div id="printable_div">';
  
  $financeinput = 0;
  $profitinput = 0;
  $interestinput = 0;
  $otherinput = 0;
  $allinput = 0;
  
  $query = db_select('finance_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$financeinput+=$node->amount;
  }
  
  $query = db_select('profit_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$profitinput+=$node->amount;
  }
  
  $query = db_select('interest_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
    $interestinput+=$node->amount;
  }

  $query = db_select('other_input', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$otherinput+=$node->amount;
  }
  
  $allinput += $financeinput;
  $allinput += $profitinput;
  $allinput += $interestinput;
  $allinput += $otherinput;

  $financeinput=number_format($financeinput, 2, '.', ','); 
  $profitinput=number_format($profitinput, 2, '.', ','); 
  $interestinput=number_format($interestinput, 2, '.', ','); 
  $otherinput=number_format($otherinput, 2, '.', ','); 
  $allinput=number_format($allinput, 2, '.', ','); 
  
  $html .= "<table style='width: 400px'><tr><th colspan=2>收入</th></tr>
  <tr><td style='width: 40%'>财政资金划入总额</td><td>".$financeinput.'(元)'."</td></tr>
  <tr><td>参股基金收入总额</td><td>".$profitinput.'(元)'."</td></tr>
  <tr><td>利息收入总额</td><td>".$interestinput.'(元)'."</td></tr>
  <tr><td>其他收入总额</td><td>".$otherinput.'(元)'."</td></tr></table>";

  //$header = array(
    //  array('data' => '基金参股支出(元)', 'field' => 'stockoutput',),
     // array('data' => '管理费划出(元)', 'field' => 'managerialoutput'),
     // array('data' => '财政资金支出(元)', 'field' => 'financeoutput'),
      // array('data' => '其他支出(元)', 'field' => 'otheroutput'),
      //array('data' => '总支出(元)', 'field' => 'alloutput'),
      //);
  $stockoutput = 0;
  $managerialoutput = 0;
  $financeoutput = 0;
  $otheroutput = 0;
  $alloutput =0;
  
  $query = db_select('stock_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$stockoutput+=$node->amount;
  }
  
  $query = db_select('managerial_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$managerialoutput+=$node->amount;
  }
  
  $query = db_select('finance_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$financeoutput+=$node->amount;
  }
  
  $query = db_select('other_output', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  foreach ($results as $node) {
  	$otheroutput+=$node->amount;
  }
  $alloutput += $stockoutput;
  $alloutput += $managerialoutput;
  $alloutput += $financeoutput;
  $alloutput += $otheroutput;
  
  $stockoutput=number_format($stockoutput, 2, '.', ','); 
  $managerialoutput=number_format($managerialoutput, 2, '.', ','); 
  $financeoutput=number_format($financeoutput, 2, '.', ','); 
  $otheroutput=number_format($otheroutput, 2, '.', ','); 
  $alloutput=number_format($alloutput, 2, '.', ','); 
  
  $html .= "<table style='width: 400px'><tr><th colspan=2>支出</th></tr>
  <tr><td style='width: 40%'>基金参股支出</td><td>".$stockoutput.'(元)'."</td></tr>
  <tr><td>管理费划出</td><td>".$managerialoutput.'(元)'."</td></tr>
  <tr><td>财政资金划出</td><td>".$financeoutput.'(元)'."</td></tr>
  <tr><td>其他支出</td><td>".$otheroutput.'(元)'."</td></tr></table>";
  
  $fudong_yingkui = 0;
  $query = db_select('fudong_yingkui', 'n') 
      ->fields ('n', array (
      'amount',
      ));
  $results = $query
      ->execute();
  //foreach ($results as $node) {
  	//$fudong_yingkui+=$node->amount;
  //}
  
  $result = $allinput - $alloutput + $fudong_yingkui;
  $fudong_yingkui=number_format($fudong_yingkui, 2, '.', ','); 
  $result=number_format($result, 2, '.', ','); 
  $html .= "<br><table style='width: 400px'><tr><td style='width: 40%'>浮动盈亏:</td><td>" .$fudong_yingkui.'(元)'.'</td></tr></table>'  .'<br>';
  $html .= "<table style='width: 400px'><tr><td style='width: 40%'>资金余额:</td><td>" .$result.'(元)'.'</td></tr></table>'  .'<br>'.'<br>';
  $html .= '</div>';
  return ($html); 
}

////////
//文件管理
////////
function jilu_file_create_jilu_page($jilu_id){
	 drupal_set_title('记录附件');
	 $page_content = '';
	 $page_content .= l('返回明细表','fundmanage/statistics') .  '<br />'. '<br />';	
	 
	 $page_content .= '<table style="width:700px"><tbody><tr><th colspan="3"> 记录附件列表</tr>';
	 if(user_access("manage fund"))
	 	$page_content .= '<tr><td width=\'55%\'>文件名称</td><td width=\'30%\'>上传时间</td><td width=\'15%\'>操作</td></tr>';
	 else
	 	$page_content .= '<tr><td width=\'55%\'>文件名称</td><td width=\'15%\'>上传时间</td><td width=\'30%\'>备注</td></tr>';
	 
     $count = 0;
     $files_array =  array();
     $query = "SELECT id, name, url, timestamp,remark FROM " .
           "{jilu_file_info} where jilu_id = ?";
	 $queryResult = db_query($query, array($jilu_id));
     foreach ($queryResult as $links ) {
	  	 $datetime = format_date($links->timestamp, 'custom', 'Y-m-d');  
	     $count += 1;
	  	 $page_content .='<tr>';
		 $page_content .= '<td>'. l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url). '</td>';		  
		 $page_content .= '<td>'. $datetime.'</td>';
		 if(user_access("manage fund"))
		 	$page_content .= '<td>'. l('编辑','jilu_file/edit/'.$links->id).'</td>';
		 else {
			 $page_content .= '<td>'.$links->remark.'</td>';
		 }
		 $page_content .='</tr>';
	 }
	 if($count == 0)
	  	$page_content .= '<tr><th colspan="4">无附件</tr>';
	 $page_content .= '</tbody></table></br>';
	 
	 $render_array = array(
	   		'#markup' => $page_content,
     );
	 if(user_access("manage fund")){
	     $form = drupal_get_form('jilu_file_create_fund_form',$jilu_id);
		 $render_array['#markup'] .= drupal_render($form);
	 }

	 return $render_array;
}

function jilu_file_create_fund_form($form, &$form_state,$jilu_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $jilu_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '上传新文件',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function jilu_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('jilu_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'file_managed_id' => $fid,
			   			 'jilu_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'jilu_file/create/jiluid/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function jilu_file_edit_page($perid) {	
  $page_content = '';
  drupal_set_title('记录附件管理');
	 
  $query = "SELECT id,name, url, jilu_id FROM " .
           "{jilu_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
	  {
	  		$page_content .= l('返回列表','jilu_file/create/fundid/'.$links->jilu_id) .  '<br />'. '<br />';	
			$ifempty = FALSE;
	  }	  
  }
  if($ifempty)
	 {
	 	drupal_goto('jilu_file/create/fundid/'.$links->id);
	 }
 else{
	 	 $page_content .= '<h5>已上传记录附件:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('jilu_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function jilu_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark, file_managed_id,jilu_id FROM " .
           "{jilu_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $jilu_id = '';
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
	$file_managed_id = $links->file_managed_id;
	$jilu_id = $links->jilu_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
	$form['jilu_id'] = array('#type' => 'hidden', '#value' => $jilu_id);	
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['jilu_file_edit_form']['name'])?$_SESSION['jilu_file_edit_form']['name']:$name,
	 );
	 
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交记录附件材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['jilu_file_edit_form']['remark'])?$_SESSION['jilu_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('jilu_file_edit_form_delete'),
	  );
		  
  return $form;
}

function jilu_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('jilu_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] =  'jilu_file/create/fundid/'.$values['jilu_id'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('jilu_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'jilu_file/create/fundid/'.$values['jilu_id'];
	}
}

function jilu_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['jilu_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['jilu_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'jilu_file/delete/'.$values['bid'];
}

//记录附件生成删除
function jilu_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除记录附件内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('jilu_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function jilu_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('jilu_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function jilu_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['jilu_file_edit_form'])){
		  	$form_state['redirect'] = 'jilu_file/create/fundid/'.$values['jilu_id'];
	  }else{
		  $values = $_SESSION['jilu_file_edit_form'];
		  unset($_SESSION['jilu_file_edit_form']);
		  $form_state['redirect'] = 'jilu_file/create/fundid/'.$values['jilu_id'];
	  }
}

function jilu_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['jilu_file_edit_form'])){
		  $form_state['redirect'] = 'jilu_file/list';
	  }else{
		  $values = $_SESSION['jilu_file_edit_form'];
		  unset($_SESSION['jilu_file_edit_form']); 
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('jilu_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'jilu_file/create/fundid/'.$values['jilu_id'];

	  }

}
